package wangjg.coco.views;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Map;

import org.eclipse.jdt.core.IJavaProject;

import wangjg.coco.PDUtil;
import wangjg.coco.PDUtil.FileClassLoader;
import wangjg.mda.gen.Preprocessor;

/**
 * 处理器工厂，返回模型附加处理器
 * @author wangjg
 *
 */
public class PreprocessorFactory {

	public static Preprocessor get(Object element){
		String fullClassName = ExplorerPreferencePage.getGenConf();
		if(fullClassName!=null && fullClassName.length()>0){
			IJavaProject jp = PDUtil.getJavaProject(element);
			FileClassLoader cl = PDUtil.getClassLoader(jp);
			try {
				Class cls = cl.findClass(fullClassName);
				if(cls!=null){
					Object obj = cls.newInstance();
					return new PreprocessorWrapper(obj);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}

class PreprocessorWrapper implements Preprocessor{
	private Object obj;
	
	public PreprocessorWrapper(Object obj) {
		this.obj = obj;
	}

	public void process(Map<String,Object> rootMap, File templFile){
		if(obj==null){
			return;
		}
		try {
			Method method = obj.getClass().getMethod("process", Map.class, File.class);
			method.invoke(obj, rootMap, templFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
